package handler

import (
	"github.com/sp-bridge/pkg/constant"
	"github.com/sp-bridge/pkg/core"
	"github.com/sp-bridge/pkg/filter"
	"github.com/sp-bridge/pkg/route"
	"sort"
)

type WebHandler interface {
	handle(exchange core.ServerWebExchange)
}

type FilteringWebHandler struct {
	globalFilters []*filter.GatewayFilter
}

func (h *FilteringWebHandler) handle(exchange core.ServerWebExchange) {
	var a = exchange.GetAttribute(constant.GATEWAY_ROUTE_ATTR)
	r, ok := a.(route.Route)
	if !ok {
		panic("获取route失败")
	}
	combined := MergeSlices(h.globalFilters, r.Filters)
	sort.Slice(combined, func(i int, j int) bool {
		return (*combined[i]).GetOrder() > (*combined[j]).GetOrder()
	})
	chain := &filter.DefaultGatewayFilterChain{Filters: combined, Index: 0}
	chain.Filter(exchange)
}

func MergeSlices(s1 []*filter.GatewayFilter, s2 []*filter.GatewayFilter) []*filter.GatewayFilter {
	slice := make([]*filter.GatewayFilter, len(s1)+len(s2))
	for i, v := range s1 {
		slice[i] = v
	}
	for i, v := range s2 {
		slice[i+len(s1)] = v
	}
	return slice
}
